﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using SalesSys.BLL;
using SalesSys.BLL.Depot;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using System.Data.Entity.Infrastructure;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 供应商
    /// </summary>
    [RoutePrefix("api/Provider")]
    public class ProviderController : BaseApiController
    {
        EmployeeBLL employeeBLL = BllFactory.GetBll<EmployeeBLL>();
        DepotCommodityBLL dcBLL = new DepotCommodityBLL();
        ProviderBLL bll = new ProviderBLL();
        private CommodityBLL commodityBLL = BllFactory.GetBll<CommodityBLL>();

        /// <summary>
        /// 获取供应商列表
        /// </summary>
        /// <param name="type">供应商类型</param>
        /// <param name="page">分页</param>
        /// <param name="rows">煤业条数</param>
        /// <returns></returns>
        public ViewDtos<Provider> Get(ProviderType? type = null, string name = null, int page = 1, int rows = 10)
        {
            ViewDtos<Provider> dto = null;
            var re = bll.QueryProviders(type, name, page, rows);
            dto = ViewDto.CreateList(re.Value);
            dto.Total = re.Key;
            dto.Rows = rows;
            dto.Page = page;
            return dto;
        }

        /// <summary>
        /// 供应商详情
        /// </summary>
        /// <param name="id">供应商编号</param>
        /// <returns></returns>
        public Provider Get(Guid id)
        {
            return bll.Details(id);
        }

        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="provider">供应商实体</param>
        public void Post(Provider provider)
        {

            var old = bll.GetList(p => p.Name == provider.Name);
            if (old.Length > 0)
            {
                throw new ApiArgException("重复的名称");
            }
            provider.DepotCommoditys = null;
            provider.Supplier = null;

            if (provider.OperationsMan != null)
            {
                provider.OperationsMan = employeeBLL.Details(provider.OperationsMan.Id);
            }
            if (provider.Manager != null)
            {
                provider.Manager = employeeBLL.Details(provider.Manager.Id);
            }
            else
            {
                throw new ApiArgException("请选择区域经理");
            }
            if (provider.MainFieldMan != null)
            {
                provider.MainFieldMan = employeeBLL.Details(provider.MainFieldMan.Id);
            }
            else
            {
                throw new ApiArgException("请选择驻厂专员");
            }
            provider.District = BllFactory.GetBll<DistrictBLL>().Details(provider.District.Id);
            if (provider.District == null)
            {
                throw new ApiArgException("仓库所在地错误");
            }
            bll.Create(provider);
        }

        /// <summary>
        /// 修改供应商信息
        /// </summary>
        /// <param name="provider">供应商实体</param>
        public void Put(Provider provider)
        {
            // var bll = new ProviderBLL();
            var entity = bll.Details(provider.Id);
            if (entity == null)
            {
                throw new ApiArgException("不存在的仓库");
            }
            entity.District = BllFactory.GetBll<DistrictBLL>().Details(provider.District.Id);
            entity.MainFieldMan = provider.MainFieldMan == null ? null : employeeBLL.Details(provider.MainFieldMan.Id);
            entity.Manager = provider.Manager == null ? null : employeeBLL.Details(provider.Manager.Id);
            entity.OperationsMan = provider.OperationsMan == null ? null : employeeBLL.Details(provider.OperationsMan.Id);
            entity.IsNonStandard = provider.IsNonStandard;
            entity.NonstandardDiscount = provider.NonstandardDiscount;
            entity.FullPaymentDiscount = provider.FullPaymentDiscount;
            bll.Edit(entity);

        }

        /// <summary>
        /// 获取供应商商品
        /// </summary>
        /// <param name="depotId">供应商编号</param>
        /// <param name="name">商品名称</param>
        /// <param name="keyStr">品牌名称</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("DepotCommodity")]
        public DepotCommodity[] GetDepotCommodity(Guid? depotId, string name = null, string keyStr = null, int page = 1, int rows = 10)
        {
            return dcBLL.GetDepotCommodityList(depotId, name, keyStr, page, rows).Value;
        }

        /// <summary>
        /// 批量修改供应商商品
        /// </summary>
        /// <param name="depotCommoditys">供应商商品</param>
        [Route("EditProviderCommodity")]
        public void EditProviderCommodity(DepotCommodity[] depotCommoditys)
        {
            var list = new List<DepotCommodity>();
            foreach (var item in depotCommoditys)
            {
                var old = dcBLL.Details(item.ProviderId, item.CommodityId);
                old.Amount = item.Amount;
                //old.Price = item.Price;
                old.MinAmount = item.MinAmount;
                old.UpdateTime = DateTime.Now;
                list.Add(old);
            }
            foreach (var item in list)
            {
                dcBLL.Edit(item);
            }
        }

        /// <summary>
        /// 提交改价审批
        /// </summary>
        /// <param name="depotCommoditys">商品数组</param>
        [Route("PriceConfirmApproval")]
        public IResultState PriceConfirmApproval(DepotCommodity[] depotCommoditys)
        {
            try
            {
                IPriceConfirmDataBLL dataBll = new PriceConfirmDataBLL();
                var emp = employeeBLL.Details(ClientHelper.ClientInfo.Id);
                var bacthId = dataBll.CreateBatch(depotCommoditys, emp);
                var data = dataBll.SelectFirst(bacthId);

                //价格审批
                SequenceApprovalBLL.PriceConfirmApproval priceConfirmApproval = new SequenceApprovalBLL.PriceConfirmApproval();
                priceConfirmApproval.Submit(data);//价格审批
                return ReState.Success.Create("提交成功");
            }
            catch (Exception e)
            {
                return ReState.Error.Create(e.Message);
            }
        }

        /// <summary>
        /// 价格审批列表
        /// </summary>
        /// <param name="batchId">批次编号</param>
        [Route("PriceConfirmDatas")]
        [HttpGet]
        public List<PriceConfirmData> PriceConfirmDatas(Guid batchId)
        {
            PriceConfirmDataBLL dataBll = new PriceConfirmDataBLL();
            var empId = ClientHelper.ClientInfo.Id;
            var re = dataBll.GetList(p => p.BatchId == batchId).ToList();
            return re;
        }

        /// <summary>
        /// 批量添加供应商商品
        /// </summary>
        /// <param name="id">供应商编号</param>
        /// <param name="dcs">商品数组</param>
        /// <returns></returns>
        [Route("AddProviderCommodity")]
        public IResultState AddProviderCommodity(Guid id, DepotCommodity[] dcs)
        {
            var commdBll = new CommodityBLL();
            var provider = bll.Details(id);

            var isdecimal = provider.DepotCommoditys.Any(
                p => dcs.FirstOrDefault(x => p.CommodityId == x.CommodityId) != null);
            if (isdecimal)
            {
                return ReState.ArgError.Create("重复添加的商品");
            }
            foreach (var item in dcs)
            {
                var commd = commdBll.Details(item.CommodityId);
                item.Commodity = commd;
                //item.Provider = provider;
                // item.ProviderId=
                item.UpdateTime = DateTime.Now;
                provider.DepotCommoditys.Add(item);

            }
            bll.Edit(provider);
            return ReState.Success.Create();
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="providerId">供应商编号</param>
        /// <param name="name">名称，模糊匹配</param>
        /// <param name="format">规格及标准，模糊匹配</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("Commodity")]
        public ViewDtos<Commodity> GetCommodity(Guid? providerId = null, string name = null, string format = null, int page = 1, int rows = 10)
        {
            var data = commodityBLL.GetList(providerId, name, format, page, rows);
            var dto = ViewDto.CreateList(data.Item2);
            dto.Page = page;
            dto.Rows = rows;
            dto.Total = data.Item1;
            return dto;
        }

        /// <summary>
        /// 出库单列表
        /// </summary>
        /// <param name="providerId">供应商编号</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("GetDeliveryLists")]
        public ViewDtos<DeliveryList> GetDeliveryLists(Guid providerId, int page = 1, int rows = 10)
        {
            var count = bll.Details(providerId).DeliveryLists.Count;
            var re = bll.Details(providerId).DeliveryLists.OrderByDescending(p => p.CreateTime).Paging(page, rows);
            var dto = ViewDto.CreateList(re);
            dto.Total = count;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 获取出库单详情
        /// </summary>
        /// <param name="deliveryListId">出库单编号</param>
        /// <returns></returns>
        [Route("GetDeliveryList")]
        public IResultState<DeliveryList> GetDeliveryList(Guid deliveryListId)
        {
            var dbll = new BaseBLL<DeliveryList, Guid>();
            var result = dbll.Details(deliveryListId);
            return ResultState.CreateSuccess(result);
        }

        /// <summary>
        /// 入库单列表
        /// </summary>
        /// <param name="providerId">供应商编号</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("GetWarehouseEntrys")]
        public ViewDtos<WarehouseEntry> GetWarehouseEntrys(Guid? providerId = null, int page = 1, int rows = 10)
        {
            var re = bll.GetWarehouseEntrys(providerId, page, rows);
            var dto = ViewDto.CreateList(re.Value);
            dto.Total = re.Key;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 创建入库单并执行入库
        /// </summary>
        /// <param name="warehouseEntry">入库单实体</param>
        /// <returns></returns>
        [Route("CreateAndRunEntry")]
        public IResultState CreateAndRunEntry(WarehouseEntry warehouseEntry)
        {
            try
            {

                IDepotBLL depotBll = new DepotBLL();
                warehouseEntry.Creater = employeeBLL.Details(ClientHelper.ClientInfo.Id);
                warehouseEntry.FromId = null;
                warehouseEntry.From = WarehouseEntrySourcce.Creater;
                warehouseEntry.Provider = bll.Details(warehouseEntry.ProviderId);
                foreach (var item in warehouseEntry.StockGoods)
                {
                    item.Commodity = commodityBLL.Details(item.Commodity.Id);
                    if (item.Commodity == null)
                    {
                        return ReState.ArgError.Create("商品不能找到");
                    }
                    item.Weight = item.TotalWeight / item.Count;
                    item.IsIn = true;
                    item.SourcePrice = item.Price;
                    item.Id = BaseTypeEx.NewTimeGuid();
                }
                var dbll = new BaseBLL<WarehouseEntry, Guid>();

                dbll.Create(warehouseEntry);

                depotBll.Entry(warehouseEntry);
                return ReState.Success.Create();
            }
            catch (DbUpdateException e)
            {
                return ReState.Error.Create("不得添加重复商品至库房");
            }
        }

        /// <summary>
        /// 冲红入库，完全抵消
        /// </summary>
        /// <param name="id">入库单编号</param>
        /// <returns></returns>
        [Route("OffsetWarehouseEntry")]
        public IResultState OffsetWarehouseEntry(Guid id)
        {

            return new DepotBLL().OffsetWarehouseEntry(id, ClientHelper.ClientInfo);

        }

        /// <summary>
        /// 获取入库单详情
        /// </summary>
        /// <param name="warehouseEntryId">入库单编号</param>
        /// <returns></returns>
        [Route("GetWarehouseEntry")]
        public IResultState<WarehouseEntry> GetWarehouseEntry(Guid warehouseEntryId)
        {
            var dbll = new BaseBLL<WarehouseEntry, Guid>();
            return ResultState.CreateSuccess(dbll.Details(warehouseEntryId));
        }


        /// <summary>
        /// 获取仓库流水
        /// </summary>
        /// <param name="providerId">供应商编号</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("GetDepotRecords")]
        public ViewDtos<DepotRecord> GetDepotRecords(Guid providerId, int page = 1, int rows = 10)
        {
            var count = bll.Details(providerId).DepotRecords.Count;
            var re = bll.Details(providerId).DepotRecords.OrderByDescending(p => p.CreateTime).Paging(page, rows);
            var dto = ViewDto.CreateList(re);
            dto.Total = count;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 仓库列表获取
        /// </summary>
        /// <param name="type">供应商类型</param>
        /// <param name="name">名称，模糊查询</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("GetWarehouse")]
        public ViewDtos<Provider> GetWarehouse(ProviderType? type = null, string name = null, int page = 1, int rows = 10)
        {
            ViewDtos<Provider> dto = null;
            var re = bll.QueryProviders(ClientHelper.ClientInfo.Id, type, name, page, rows);
            dto = ViewDto.CreateList(re.Value);
            dto.Total = re.Key;
            dto.Rows = rows;
            dto.Page = page;
            return dto;
        }
    }
}
